package tau.pimpmyfreedb.GUI;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class TextInputDialog {
	private Shell parent;
	private Shell shell;
	private Label label;
	private Button bOk, bCancel;
	private Text text;
	private boolean answer; 
	private String ans;
	
	public TextInputDialog(Shell parent) {
		
		this.parent = parent;
		shell = CreateShell(parent);
	}

	public void run(String msg){
		
		label.setText(msg);
		if (parent != null)
			parent.setEnabled(false);
		shell.open();
		shell.pack();
		text.setSelection(0, text.getText().length()  );
		text.setFocus();
		SWTUtil.readAndDispatch(new Predicate() {
			
			@Override
			public boolean isTrue() {				
				return !shell.isDisposed();
			}
		});
	}
	private Shell CreateShell(Shell parent2) {
		shell = SWTUtil.getDialog(parent);
		shell.setLocation(200, 200);
		
		GridLayout gl = new GridLayout(2, false);
//		gl.marginWidth = 40;
//		gl.marginHeight = 20;
		shell.setLayout(gl);
		
		label = new Label(shell, SWT.NONE);
		GridData gridData = new GridData();
		gridData.grabExcessHorizontalSpace = true;
		gridData.horizontalAlignment = SWT.FILL;
		label.setLayoutData(gridData);
		
		text = new Text(shell, SWT.BORDER);
		gridData = new GridData();
		gridData.grabExcessHorizontalSpace = true;
		gridData.horizontalAlignment = SWT.FILL;
		text.setLayoutData(gridData);
		text.setText("Please enter new entry");
		
		bCancel = new Button(shell, SWT.PUSH);
		bCancel.setText("Cancel");
		gridData = new GridData();
		gridData.horizontalAlignment = SWT.LEFT;
		gridData.grabExcessHorizontalSpace = true;
		bCancel.setLayoutData(gridData);
		bCancel.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				answer = false;
				close();
			}


		});
		
		bOk = new Button(shell, SWT.PUSH);
		bOk.setText("OK");
		gridData = new GridData();
		gridData.horizontalAlignment = SWT.RIGHT;
		bOk.setLayoutData(gridData);
		bOk.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				answer = true;
				close();
			}


		});

		shell.pack();
		
		return shell;
	}
	
	public String getInput(){
		if (answer)
		{
			return ans;
		}
		return null;
	}
	
	public void close() {
		ans = text.getText();
		shell.dispose();
		if (parent != null) {
			parent.setEnabled(true);
			parent.setFocus();
		}				
	}

}
